import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/androidUpdata/viewModel/UpdataViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/utils/ApkUpdataUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:path_provider/path_provider.dart';

class UpdataView extends BaseStatefulWidget {
  var version;

  UpdataView({Key key, this.version});

  @override
  State<StatefulWidget> initState() {
    return UpdataViewState();
  }
}

class UpdataViewState extends BaseState<UpdataViewModel, UpdataView> {

  @override
  Widget initWidget() {
    return Scaffold(
      appBar: MTopBar(
        leftButtonIcon: Icons.arrow_back,
        onLeftButtonIconClick: () {
          Navigator.pop(context);
        },
        title: "版本更新",
      ).create(),
      body: _bodyView(),
    );
  }

  _bodyView() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Expanded(
          flex: 1,
          child: _dialogBody(widget.version.version.whatsNew),
        ),
        Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: FlatButton(
                  child: Text(isDownloading ? "取消" : "现在更新"),
                  onPressed: () {
                    setState(() {
                      if (!isDownloading) {
                        isDownloading = true;
                        if (widget.version.getDownloadUrl() == "") {
                          this.count = 0;
                          this.total = 0;
                          isDownloading = false;
                          ToastUtils.showToast("下载地址为空");
                          Navigator.pop(context);
                        } else {
                          _download(context, widget.version.getDownloadUrl());
                        }
                      } else {
                        this.count = 0;
                        this.total = 0;
                        isDownloading = false;
                        Navigator.of(context).pop();
                        if (widget.version.supported == 0) {
                          // 强制更新退出登录
                          exit(0);
                        }
                      }
                    });
                  }),
            ),
            Expanded(
              flex: 1,
              child: Offstage(
                offstage: isDownloading,
                child: new FlatButton(
                    child: new Text("稍后再说"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      if (widget.version.supported == 0) {
                        // 强制更新退出登录
                        exit(0);
                      }
                    }),
              ),
            )
          ],
        )
      ],
    );
  }

  bool isDownloading = false;
  String apkPath = "";
  int count, total;

  _dialogBody(String words) {
    if (isDownloading) {
      try {
        int progress = (count / total * 100).toInt();
        return Container(
            margin: EdgeInsets.all(Dimens.dimens16),
            child: Text("下载进度：$progress%"));
      } catch (e) {
        return Container(
            margin: EdgeInsets.all(Dimens.dimens16), child: Text("下载进度：0%"));
      }
    } else {
      List<String> list = List();
      list.addAll(words.split("<abc>"));

      return Container(
        margin: EdgeInsets.all(Dimens.dimens16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: _getItems(list),
        ),
      );
    }
  }

  List<Widget> _getItems(List<String> list) {
    // 不带分割线的item
    List<Widget> items = new List();
    for (int i = 0; i < list.length; i++) {
      items.add(Container(
        padding: EdgeInsets.only(top: Dimens.dimens4, bottom: Dimens.dimens4),
        child: Text(list[i]),
      ));
    }
    return items;
  }

  //开始下载附件
  void _download(BuildContext context, String downPath) async {
    final dir = await getExternalStorageDirectory();
    apkPath = dir.path + '/ehs2.apk';
    print(apkPath);
    Dio dio = new Dio();
    Response response = await dio.download(downPath, apkPath,
        onReceiveProgress: (count, total) {
      setState(() {
        this.count = count;
        this.total = total;
        if (count == total) {
          // 下载完毕
          ApkUpdataUtils.install(apkPath);
          isDownloading = false;
          Navigator.of(context).pop();
        }
      });
    });
  }
}
